import React, { useRef, useState } from 'react'
import { Button, NavBar, Form, Input, List, Toast } from 'antd-mobile'
import { AxiosError } from 'axios'
import styles from './index.module.scss'
import { useDispatch } from 'react-redux'
import { getLogin, SendMessage } from '@/store/actions/login'
import { LoginMessage } from '@/types/store'
import { useHistory } from 'react-router'
import { InputRef } from 'antd-mobile/es/components/input'
import { useTimer } from '@/utils/jishiqi'
const Login = () => {
  const [isDown, setisDown] = useState(false)
  const [form] = Form.useForm()
  const dispatch = useDispatch()
  const history = useHistory()
  const refForm = useRef<InputRef>(null)
  const { num, start } = useTimer(4, () => { setisDown(false) })
  // 点击提交登录
  const onFinish = async (val: LoginMessage) => {
    try {
      // 1 请求数据
      await dispatch(getLogin(val))
      // 2 提示成功
      Toast.show({
        icon: 'success',
        content: '登录成功'
      })
      // 3 路由跳转
      history.push('/layout')
    } catch (err) {
      const error = err as AxiosError<{ message: string }>
      Toast.show({
        icon: 'fail',
        content: error.response!.data.message
      })
    }
  }
  // a 发验证码
  const onMoblieClick = () => {
    // 1 拿到手机号
    const mobile = form.getFieldValue('mobile')
    // 2 判断校验是成功还是失败  0 格式正确,发请求   1 格式错误 提示格式错误
    form.getFieldError('mobile').length ? mistake() : correct(mobile)
  }

  // a1 格式正确,发请求
  const correct = async (mobile: string) => {
    // 1 禁用按钮
    setisDown(true)
    // 2 发请求
    try {
      await dispatch(SendMessage(mobile))
      // 2.1 发短信成功
      Toast.show({
        icon: 'success',
        content: '短信发送成功'
      })
    } catch (err) {
      const error = err as AxiosError<{ message: string }>
      // 2.2 短信频繁失败
      Toast.show({
        icon: 'fail',
        content: error.response?.data.message
      })
    }

    // 3 启用定时器开始倒计时
    start()
  }

  // a2 格式错误 提示格式错误
  const mistake = () => {
    // 表单获取光标聚集
    refForm.current?.focus()

    Toast.show({
      icon: 'fail',
      content: '手机验证失败'
    })
  }

  return (
    <div className={styles.root}>
      <NavBar />

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form
          form={form}
          onFinish={onFinish}
          initialValues={{ mobile: '13911111211', code: '246810' }}>
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              { required: true, message: '手机号不能为空' },
              {
                pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                message: '手机格式不正确'
              }
            ]}>
            <Input ref={refForm} placeholder="请输入手机号" />
          </Form.Item>

          <List.Item
            className="login-code-extra"
            extra={<button disabled={isDown} className="code-extra" onClick={onMoblieClick}>{isDown ? `还有${num}秒可重新发送` : '发送验证码'}</button>}>
            <Form.Item
              name="code"
              className="login-item"
              rules={[{ required: true, message: '验证码不能为空' }, { pattern: /^\d{6}$/, message: '验证码需六位生效' }]}>
              <Input placeholder="请输入验证码" autoComplete="off" />
            </Form.Item>
          </List.Item>

          <Form.Item noStyle>
            <Button
              block
              type="submit"
              color="primary"
              className="login-submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
